<template>
  <div class="delivery-admin-tasks">
    <el-main>
      <div class="header">
        <h2>配送任务管理</h2>
        <div class="actions">
          <el-button 
            type="success" 
            :style="{ backgroundColor: '#0f9b0f', borderColor: '#0f9b0f' }" 
            @click="refreshDeliveries"
          >刷新数据</el-button>
          <el-button 
            type="success" 
            :style="{ backgroundColor: '#0f9b0f', borderColor: '#0f9b0f' }" 
            @click="exportData"
          >导出报表</el-button>
        </div>
      </div>

      <!-- 搜索和筛选 -->
      <el-card class="filter-card">
        <el-form :inline="true" :model="filterForm" class="filter-form">
          <el-form-item label="配送编号">
            <el-input v-model="filterForm.delivery_number" placeholder="配送编号" clearable></el-input>
          </el-form-item>
          <el-form-item label="订单编号">
            <el-input v-model="filterForm.order_number" placeholder="订单编号" clearable></el-input>
          </el-form-item>
          <el-form-item label="客户名称">
            <el-input v-model="filterForm.customer_name" placeholder="客户名称" clearable></el-input>
          </el-form-item>
          <el-form-item label="配送员">
            <el-select
              v-model="filterForm.deliveryman_id"
              placeholder="选择配送员"
              clearable
              filterable
              :filter-method="filterDeliveryman"
              :remote="false"
            >
              <el-option
                v-for="staff in filteredDeliveryStaff"
                :key="staff.id"
                :label="`${staff.id} (${staff.user.username})`"
                :value="staff.user.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="filterForm.status"
              placeholder="选择状态"
              clearable
              filterable
              :filter-method="filterStatus"
              :remote="false"
            >
              <el-option
                v-for="item in filteredStatusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="优先级">
            <el-select
              v-model="filterForm.priority"
              placeholder="选择优先级"
              clearable
              filterable
              :filter-method="filterPriority"
              :remote="false"
            >
              <el-option
                v-for="item in filteredPriorityOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="filterForm.date_range"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item>
            <el-button 
              type="success" 
              :style="{ backgroundColor: '#0f9b0f', borderColor: '#0f9b0f' }" 
              @click="handleFilter"
            >筛选</el-button>
            <el-button 
              type="success" 
              :style="{ backgroundColor: '#0f9b0f', borderColor: '#0f9b0f' }" 
              @click="resetFilter"
            >重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="6" animated />
      </div>

      <!-- 配送任务列表 -->
      <el-table 
        v-else 
        :data="deliveries" 
        style="width: 100%"
        border
        stripe
        highlight-current-row
        @row-click="handleRowClick"
      >
        <el-table-column prop="delivery_number" label="配送编号" width="150" sortable />
        <el-table-column prop="order_number" label="关联订单" width="150" sortable />
        <el-table-column prop="customer_name" label="客户名称" width="120" />
        <el-table-column prop="address" label="配送地址" min-width="200" show-overflow-tooltip />
        <el-table-column prop="deliveryman_name" label="配送员" width="120">
          <template #default="scope">
            <el-tag v-if="scope.row.deliveryman_name" type="info">{{ scope.row.deliveryman_name }}</el-tag>
            <el-tag v-else type="danger">未分配</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="140">
           <template #default="scope">
            <div>
              <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
              <el-tag v-if="scope.row.status === 'awaiting_manual_assignment'" type="danger" effect="dark" class="ml-1">需手动分配</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" width="80">
          <template #default="scope">
            <el-tag 
              :type="scope.row.priority === 'high' ? 'danger' : scope.row.priority === 'medium' ? 'warning' : 'info'"
            >
              {{ scope.row.priority === 'high' ? '高' : scope.row.priority === 'medium' ? '中' : '低' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180" sortable />
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="scope">
            <el-button size="small" @click.stop="handleViewDetail(scope.row)">查看</el-button>
            <el-button 
              size="small" 
              type="success" 
              @click.stop="handleAssignDelivery(scope.row)"
              :disabled="scope.row.status !== 'pending' && scope.row.status !== 'awaiting_manual_assignment'"
            >
              分配
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalItems"
        />
      </div>

      <!-- 新建/编辑配送任务对话框 -->
      <el-dialog
        v-model="dialogVisible"
        title="新建配送任务"
        width="50%"
      >
        <el-form :model="deliveryForm" label-width="100px">
          <el-form-item label="关联订单">
            <el-select v-model="deliveryForm.sales_order" placeholder="请选择订单" filterable>
              <el-option
                v-for="order in availableOrders"
                :key="order.id"
                :label="`${order.order_number} - ${order.customer_name}`"
                :value="order.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="优先级">
            <el-select v-model="deliveryForm.priority" placeholder="请选择优先级">
              <el-option label="高" value="high" />
              <el-option label="中" value="medium" />
              <el-option label="低" value="low" />
            </el-select>
          </el-form-item>
          <el-form-item label="预计配送时间">
            <el-date-picker
              v-model="deliveryForm.estimated_delivery_time"
              type="datetime"
              placeholder="选择日期时间"
            />
          </el-form-item>
          <el-form-item label="备注">
            <el-input type="textarea" v-model="deliveryForm.note" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmitDelivery">确定</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 分配配送员对话框 -->
      <el-dialog
        v-model="assignDialogVisible"
        title="分配配送员"
        width="50%"
      >
        <el-form :model="assignForm" label-width="100px">
          <el-form-item label="配送任务">
            <span>{{ assignForm.delivery_number }}</span>
          </el-form-item>
          <el-form-item label="配送员">
            <el-select
              v-model="assignForm.deliveryman_id"
              placeholder="请选择配送员"
              filterable
              :filter-method="filterDeliveryman"
              :remote="false"
            >
              <el-option
                v-for="staff in filteredDeliveryStaff"
                :key="staff.id"
                :label="`${staff.id} (${staff.user.username})`"
                :value="staff.user.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="优先级">
            <el-select v-model="assignForm.priority" placeholder="请选择优先级">
              <el-option label="高" value="high" />
              <el-option label="中" value="medium" />
              <el-option label="低" value="low" />
            </el-select>
          </el-form-item>
          <el-form-item label="预计配送时间">
            <el-date-picker
              v-model="assignForm.estimated_delivery_time"
              type="datetime"
              placeholder="选择日期时间"
            />
          </el-form-item>
          <el-form-item label="备注">
            <el-input type="textarea" v-model="assignForm.note" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="assignDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmitAssign">确定</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 任务详情对话框 -->
      <el-dialog
        v-model="detailDialogVisible"
        title="配送任务详情"
        width="60%"
      >
        <el-descriptions :column="2" border>
          <el-descriptions-item label="配送编号">{{ currentTask.delivery_number }}</el-descriptions-item>
          <el-descriptions-item label="关联订单">{{ currentTask.order_number }}</el-descriptions-item>
          <el-descriptions-item label="客户名称">{{ currentTask.customer_name }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ currentTask.customer_phone }}</el-descriptions-item>
          <el-descriptions-item label="配送地址" :span="2">{{ currentTask.address }}</el-descriptions-item>
          <el-descriptions-item label="配送员">{{ currentTask.deliveryman_name || '未分配' }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(currentTask.status)">{{ getStatusText(currentTask.status) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="优先级">
            <el-tag 
              :type="currentTask.priority === 'high' ? 'danger' : currentTask.priority === 'medium' ? 'warning' : 'info'"
            >
              {{ currentTask.priority === 'high' ? '高' : currentTask.priority === 'medium' ? '中' : '低' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="预计配送时间">{{ currentTask.estimated_delivery_time || '未设置' }}</el-descriptions-item>
          <el-descriptions-item label="实际配送时间">{{ currentTask.actual_delivery_time || '未完成' }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ currentTask.note || '无' }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ currentTask.created_at }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ currentTask.updated_at }}</el-descriptions-item>
        </el-descriptions>

        <div class="task-history" v-if="taskHistory.length > 0">
          <h3>状态变更历史</h3>
          <el-timeline>
            <el-timeline-item
              v-for="(history, index) in taskHistory"
              :key="index"
              :timestamp="formatDateTime(history.created_at)"
              :type="getStatusType(history.status)"
            >
              状态变更为 {{ getStatusText(history.status) }}
              <div v-if="history.note" class="history-note">备注: {{ history.note }}</div>
            </el-timeline-item>
          </el-timeline>
        </div>
      </el-dialog>
    </el-main>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { getToken } from '@/utils/auth'
import { useRoute } from 'vue-router'
import * as XLSX from 'xlsx'

const route = useRoute()

// 配送任务列表数据
const deliveries = ref([]) // 当前页数据
const allDeliveries = ref([]) // 全量数据
const loading = ref(false)

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const totalItems = ref(0)

// 可用订单列表
const availableOrders = ref([])

// 配送员列表
const deliveryStaff = ref([])

// 筛选表单
const filterForm = ref({
  delivery_number: '',
  order_number: '',
  customer_name: '',
  deliveryman_id: '',
  status: '',
  priority: '',
  date_range: []
})

// 对话框相关
const dialogVisible = ref(false)
const deliveryForm = ref({
  sales_order: '',
  priority: 'medium',
  estimated_delivery_time: '',
  note: ''
})

// 分配对话框相关
const assignDialogVisible = ref(false)
const assignForm = ref({
  id: '',
  delivery_number: '',
  deliveryman_id: '',
  priority: '',
  estimated_delivery_time: '',
  note: ''
})

// 详情对话框相关
const detailDialogVisible = ref(false)
const currentTask = ref({})
const taskHistory = ref([])

// 添加本地模糊搜索逻辑
const filteredDeliveryStaff = ref([])

// 在<script setup>中添加状态和优先级的本地搜索逻辑
const statusOptions = [
  { label: '待分配', value: 'pending' },
  { label: '已分配', value: 'assigned' },
  { label: '已拒绝', value: 'rejected' },
  { label: '等待手动分配', value: 'awaiting_manual_assignment' },
  { label: '配送中', value: 'delivering' },
  { label: '已完成', value: 'completed' },
  { label: '已取消', value: 'cancelled' }
]
const filteredStatusOptions = ref([...statusOptions])
const filterStatus = (query) => {
  if (!query) {
    filteredStatusOptions.value = [...statusOptions]
  } else {
    const q = query.toLowerCase()
    filteredStatusOptions.value = statusOptions.filter(item =>
      item.label.toLowerCase().includes(q) || item.value.includes(q)
    )
  }
}

const priorityOptions = [
  { label: '高', value: 'high' },
  { label: '中', value: 'medium' },
  { label: '低', value: 'low' }
]
const filteredPriorityOptions = ref([...priorityOptions])
const filterPriority = (query) => {
  if (!query) {
    filteredPriorityOptions.value = [...priorityOptions]
  } else {
    const q = query.toLowerCase()
    filteredPriorityOptions.value = priorityOptions.filter(item =>
      item.label.toLowerCase().includes(q) || item.value.includes(q)
    )
  }
}

// 初始化时显示全部
onMounted(() => {
  filteredDeliveryStaff.value = deliveryStaff.value
})

// 监听deliveryStaff变化
watch(deliveryStaff, (val) => {
  filteredDeliveryStaff.value = val
})

// 搜索方法
const filterDeliveryman = (query) => {
  if (!query) {
    filteredDeliveryStaff.value = deliveryStaff.value
  } else {
    const q = query.toLowerCase()
    filteredDeliveryStaff.value = deliveryStaff.value.filter(staff =>
      (staff.user.username && staff.user.username.toLowerCase().includes(q)) ||
      (String(staff.id).includes(q))
    )
  }
}

// 获取状态样式
const getStatusType = (status) => {
  const statusMap = {
    'pending': 'warning',
    'assigned': 'info',
    'rejected': 'danger',
    'awaiting_manual_assignment': 'danger',
    'delivering': 'primary',
    'completed': 'success',
    'cancelled': 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'pending': '待分配',
    'assigned': '已分配',
    'rejected': '已拒绝',
    'awaiting_manual_assignment': '等待手动分配',
    'delivering': '配送中',
    'completed': '已完成',
    'cancelled': '已取消'
  }
  return statusMap[status] || status
}

// 构建查询参数
const buildQueryParams = () => {
  const params = {
    page: currentPage.value,
    page_size: pageSize.value
  }
  
  if (filterForm.value.delivery_number) {
    params.delivery_number__icontains = filterForm.value.delivery_number.trim()
    console.log('添加配送编号筛选条件:', filterForm.value.delivery_number.trim())
  }
  
  if (filterForm.value.order_number) {
    params.order_number = filterForm.value.order_number
  }
  
  if (filterForm.value.customer_name) {
    params.customer_name = filterForm.value.customer_name
  }
  
  if (filterForm.value.deliveryman_id) {
    params.deliveryman = filterForm.value.deliveryman_id
  }
  
  if (filterForm.value.status) {
    params.status = filterForm.value.status
  }
  
  if (filterForm.value.priority) {
    params.priority = filterForm.value.priority
  }
  
  if (filterForm.value.date_range && filterForm.value.date_range.length === 2) {
    params.start_date = filterForm.value.date_range[0]
    params.end_date = filterForm.value.date_range[1]
  }

  console.log('最终构建的查询参数:', params)
  return params
}

// 获取配送任务列表（一次性拉取全部数据）
const fetchDeliveries = async () => {
  loading.value = true
  try {
    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      loading.value = false
      return
    }
    // 拉取全部数据（不分页）
    const response = await axios.get('/api/delivery-tasks/', {
      params: { page: 1, page_size: 10000 },
      headers: { 'Authorization': `Bearer ${token}` }
    })
    if (response.data.code === 200) {
      allDeliveries.value = response.data.data.items || []
      filterDeliveries() // 初始渲染
    } else {
      ElMessage.error(response.data.message || '获取配送任务列表失败')
      allDeliveries.value = []
      deliveries.value = []
      totalItems.value = 0
    }
  } catch (error) {
    console.error('获取配送任务列表出错:', error)
    allDeliveries.value = []
    deliveries.value = []
    totalItems.value = 0
    ElMessage.error('获取配送任务列表失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 新增前端本地筛选和分页
const filterDeliveries = () => {
  let filtered = allDeliveries.value
  // 配送编号
  if (filterForm.value.delivery_number) {
    const q = filterForm.value.delivery_number.trim().toLowerCase()
    filtered = filtered.filter(d => (d.delivery_number || '').toLowerCase().includes(q))
  }
  // 订单编号
  if (filterForm.value.order_number) {
    const q = filterForm.value.order_number.trim().toLowerCase()
    filtered = filtered.filter(d => (d.order_number || '').toLowerCase().includes(q))
  }
  // 客户名称
  if (filterForm.value.customer_name) {
    const q = filterForm.value.customer_name.trim().toLowerCase()
    filtered = filtered.filter(d => (d.customer_name || '').toLowerCase().includes(q))
  }
  // 配送员
  if (filterForm.value.deliveryman_id) {
    filtered = filtered.filter(d => String(d.deliveryman) === String(filterForm.value.deliveryman_id))
  }
  // 状态
  if (filterForm.value.status) {
    filtered = filtered.filter(d => d.status === filterForm.value.status)
  }
  // 优先级
  if (filterForm.value.priority) {
    filtered = filtered.filter(d => d.priority === filterForm.value.priority)
  }
  // 创建时间范围
  if (filterForm.value.date_range && filterForm.value.date_range.length === 2) {
    const [start, end] = filterForm.value.date_range
    filtered = filtered.filter(d => {
      const date = d.created_at ? d.created_at.slice(0, 10) : ''
      return date >= start && date <= end
    })
  }
  totalItems.value = filtered.length
  // 分页
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  deliveries.value = filtered.slice(start, end)
}

// 获取可用订单列表
const fetchAvailableOrders = async () => {
  try {
    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }
    
    const response = await axios.get('/api/orders/', {
      params: {
        status: 'paid',
        has_delivery: false
      },
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    
    if (response.data.code === 200) {
      availableOrders.value = response.data.data.items
    } else {
      ElMessage.error(response.data.message || '获取可用订单列表失败')
    }
  } catch (error) {
    console.error('获取可用订单列表出错:', error)
    ElMessage.error('获取可用订单列表失败: ' + error.message)
  }
}

// 获取配送员列表
const fetchDeliveryStaff = async () => {
  try {
    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }
    
    const response = await axios.get('/api/delivery-staff', {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    
    if (response && response.data) {
      if (Array.isArray(response.data)) {
        deliveryStaff.value = response.data
      } 
      else if (response.data.results && Array.isArray(response.data.results)) {
        deliveryStaff.value = response.data.results
      }
      else if (response.data.data && Array.isArray(response.data.data)) {
        deliveryStaff.value = response.data.data
      }
      else {
        console.warn('配送员数据格式不是预期的数组格式')
        deliveryStaff.value = []
      }
    } else {
      console.error('获取配送员列表失败，响应数据格式不正确')
      deliveryStaff.value = []
    }
  } catch (error) {
    console.error('获取配送员列表出错:', error)
    deliveryStaff.value = []
    ElMessage.error('获取配送员列表失败: ' + (error.response?.data?.detail || error.message || '未知错误'))
  }
}

// 获取任务状态历史
const fetchTaskHistory = async (taskId) => {
  try {
    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }
    
    console.log('开始获取任务ID:', taskId, '的历史记录')
    
    const response = await axios.get(`/api/delivery-status-records/`, {
      params: { delivery_task: taskId },
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    
    console.log('任务历史响应数据类型:', typeof response.data)
    console.log('任务历史响应数据结构:', JSON.stringify(response.data))
    
    if (response.data.code === 200 && response.data.data && response.data.data.items) {
      console.log('使用 code/data/items 格式处理数据')
      taskHistory.value = response.data.data.items
    } else if (Array.isArray(response.data)) {
      console.log('使用数组格式处理数据')
      taskHistory.value = response.data
    } else if (response.data.results && Array.isArray(response.data.results)) {
      console.log('使用 results 格式处理数据')
      taskHistory.value = response.data.results
    } else if (response.data.items && Array.isArray(response.data.items)) {
      console.log('使用 items 格式处理数据')
      taskHistory.value = response.data.items
    } else if (response.data.data && Array.isArray(response.data.data)) {
      console.log('使用 data 数组格式处理数据')
      taskHistory.value = response.data.data
    } else if (response.data.status_records && Array.isArray(response.data.status_records)) {
      console.log('使用 status_records 格式处理数据')
      taskHistory.value = response.data.status_records
    } else {
      console.log('尝试从当前任务中获取状态记录')
      if (currentTask.value && currentTask.value.status_records && Array.isArray(currentTask.value.status_records)) {
        console.log('从当前任务对象中获取状态记录成功')
        taskHistory.value = currentTask.value.status_records
      } else {
        taskHistory.value = []
        console.error('无法识别的任务历史数据格式:', response.data)
        ElMessage.error('获取任务历史失败: 数据格式不正确')
      }
    }
    
    if (taskHistory.value.length > 0) {
      console.log('排序前的历史记录:', JSON.stringify(taskHistory.value))
      taskHistory.value.sort((a, b) => new Date(a.created_at) - new Date(b.created_at))
      console.log('排序后的历史记录数量:', taskHistory.value.length)
      console.log('排序后的历史记录状态:', taskHistory.value.map(item => item.status).join(', '))
      
      console.log('历史记录时间详情:', taskHistory.value.map(item => {
        return {
          status: item.status,
          created_at: item.created_at,
          created_at_date: new Date(item.created_at).toLocaleString()
        }
      }))
    }
  } catch (error) {
    console.error('获取任务历史出错:', error)
    taskHistory.value = []
    ElMessage.error('获取任务历史失败: ' + error.message)
  }
}

// 刷新配送任务列表
const refreshDeliveries = async () => {
  try {
    await fetchDeliveries()
    ElMessage.success('数据已更新')
  } catch (error) {
    console.error('刷新数据失败:', error)
    ElMessage.error('刷新数据失败: ' + error.message)
  }
}

// 处理筛选
const handleFilter = () => {
  currentPage.value = 1
  filterDeliveries()
}

// 重置筛选
const resetFilter = () => {
  filterForm.value = {
    delivery_number: '',
    order_number: '',
    customer_name: '',
    deliveryman_id: '',
    status: '',
    priority: '',
    date_range: []
  }
  currentPage.value = 1
  filterDeliveries()
}

// 处理新建配送任务
const handleAddDelivery = () => {
  dialogVisible.value = true
  deliveryForm.value = {
    sales_order: '',
    priority: 'medium',
    estimated_delivery_time: '',
    note: ''
  }
  fetchAvailableOrders()
}

// 处理查看详情
const handleViewDetail = (row) => {
  currentTask.value = row
  detailDialogVisible.value = true
  fetchTaskHistory(row.id)
}

// 处理行点击
const handleRowClick = (row) => {
  handleViewDetail(row)
}

// 处理分配配送员
const handleAssignDelivery = (row) => {
  assignDialogVisible.value = true
  assignForm.value = {
    id: row.id,
    delivery_number: row.delivery_number,
    deliveryman_id: row.deliveryman?.id || '',
    priority: row.priority,
    estimated_delivery_time: row.estimated_delivery_time,
    note: row.note
  }
  fetchDeliveryStaff()
}

// 提交配送任务
const handleSubmitDelivery = async () => {
  try {
    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }
    
    if (!deliveryForm.value.sales_order) {
      ElMessage.warning('请选择关联订单')
      return
    }
    
    const response = await axios.post('/api/delivery-tasks/', deliveryForm.value, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    
    if (response.data.code === 200) {
      ElMessage.success('创建成功')
      dialogVisible.value = false
      fetchDeliveries()
    } else {
      ElMessage.error(response.data.message || '创建失败')
    }
  } catch (error) {
    console.error('创建配送任务出错:', error)
    if (error.response && error.response.data) {
      console.error('后端返回的错误详情:', error.response.data)
      ElMessage.error('创建失败: ' + JSON.stringify(error.response.data))
    } else {
      ElMessage.error('创建失败: ' + error.message)
    }
  }
}

// 提交分配配送员
const handleSubmitAssign = async () => {
  try {
    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }
    
    if (!assignForm.value.deliveryman_id) {
      ElMessage.warning('请选择配送员')
      return
    }
    
    console.log('提交的分配数据:', {
      id: assignForm.value.id,
      deliveryman_id: assignForm.value.deliveryman_id,
      priority: assignForm.value.priority,
      estimated_delivery_time: assignForm.value.estimated_delivery_time,
      note: assignForm.value.note
    })
    
    const response = await axios.post(
      `/api/delivery-tasks/${assignForm.value.id}/assign/`,
      {
        deliveryman_id: assignForm.value.deliveryman_id,
        priority: assignForm.value.priority,
        estimated_delivery_time: assignForm.value.estimated_delivery_time,
        note: assignForm.value.note
      },
      {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      }
    )
    
    if (response.data.code === 200) {
      ElMessage.success('分配成功')
      assignDialogVisible.value = false
      fetchDeliveries()
    } else {
      ElMessage.error(response.data.message || '分配失败')
    }
  } catch (error) {
    console.error('分配配送员出错:', error)
    if (error.response) {
      console.error('错误状态码:', error.response.status)
      console.error('错误详情:', error.response.data)
    }
    ElMessage.error('分配失败: ' + error.message)
  }
}

// 导出报表
const exportData = () => {
  // 导出全部筛选后的数据（allDeliveries）
  if (!allDeliveries.value || allDeliveries.value.length === 0) {
    ElMessage.warning('无可导出的数据')
    return
  }
  // 只导出表格展示的主要字段
  const exportFields = [
    { label: '配送编号', key: 'delivery_number' },
    { label: '关联订单', key: 'order_number' },
    { label: '客户名称', key: 'customer_name' },
    { label: '配送地址', key: 'address' },
    { label: '配送员', key: 'deliveryman_name' },
    { label: '状态', key: 'status' },
    { label: '优先级', key: 'priority' },
    { label: '创建时间', key: 'created_at' }
  ]
  const data = allDeliveries.value.map(row => {
    const obj = {}
    exportFields.forEach(f => {
      if (f.key === 'status') {
        obj[f.label] = getStatusText(row.status)
      } else if (f.key === 'priority') {
        obj[f.label] = row.priority === 'high' ? '高' : row.priority === 'medium' ? '中' : '低'
      } else if (f.key === 'deliveryman_name') {
        // 兼容多种后端结构
        obj[f.label] = row.deliveryman_name || (row.deliveryman && row.deliveryman.user && row.deliveryman.user.username) || (row.deliveryman && row.deliveryman.username) || ''
      } else {
        obj[f.label] = row[f.key] || ''
      }
    })
    return obj
  })
  const ws = XLSX.utils.json_to_sheet(data)
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, '配送任务')
  XLSX.writeFile(wb, `配送任务报表_${new Date().toISOString().split('T')[0]}.xlsx`)
  ElMessage.success('导出成功')
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  filterDeliveries()
}

// 处理每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  filterDeliveries()
}

// 页面加载时获取数据
onMounted(async () => {
  try {
    await fetchDeliveryStaff()
    await fetchDeliveries()
    // 检查URL中是否有任务ID参数
    const taskId = route.query.task_id
    if (taskId) {
      await fetchTaskById(taskId)
    }
  } catch (error) {
    console.error('初始化数据加载失败:', error)
    ElMessage.error('数据加载失败: ' + error.message)
  }
})

// 根据ID获取任务
const fetchTaskById = async (taskId) => {
  try {
    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }
    
    const response = await axios.get(`/api/delivery-tasks/${taskId}/`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    
    if (response.data.code === 200) {
      const task = response.data.data
      handleViewDetail(task)
    } else {
      ElMessage.error(response.data.message || '获取任务详情失败')
    }
  } catch (error) {
    console.error('获取任务详情出错:', error)
    ElMessage.error('获取任务详情失败: ' + error.message)
  }
}

// 添加时间格式化函数
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '未知时间';
  try {
    const date = new Date(dateTimeStr);
    return date.toLocaleString();
  } catch (e) {
    console.error('日期格式化错误:', e);
    return dateTimeStr;
  }
}
</script>

<style scoped>
.delivery-admin-tasks {
  height: 80px;
  width: 100%;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.actions {
  display: flex;
  gap: 10px;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  justify-content: space-between;
}

.filter-form .el-form-item {
  margin-right: 0;
  margin-bottom: 10px;
  flex-basis: 32%;
}

.filter-form .el-form-item:last-child {
  flex-basis: 100%;
  display: flex;
  justify-content: flex-end;
  margin-bottom: 0;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.loading-container {
  padding: 20px;
}

.task-history {
  margin-top: 20px;
}

.history-note {
  font-size: 12px;
  color: #666;
  margin-top: 5px;
}
</style>